#include <stdio.h>
#include "e_mqtt.h"
#include "e_wifi_sta.h"


esp_mqtt_client_config_t clientConfig = {
        .broker.address.uri = "mqtt://192.168.1.12",
        .broker.address.port = 1883,
        .broker.address.path = "/mqtt",
        .credentials.client_id = "esp001",
        .credentials.username = "root",
        .credentials.authentication.password = "root"
};

esp_mqtt_client_handle_t clientHandle;


void mqtt_event_handel(void *event_handler_arg,
                       esp_event_base_t event_base,
                       int32_t event_id,
                       void *event_data) {
    esp_mqtt_event_handle_t event = event_data;
    esp_mqtt_client_handle_t client = event->client;

    switch ((esp_mqtt_event_id_t) event_id) {
        case MQTT_EVENT_ERROR:
            ESP_LOGI("MQTT_EVENT", "MQTT_EVENT_ERROR");
            break;
        case MQTT_EVENT_CONNECTED:
            ESP_LOGI("MQTT_EVENT", "MQTT_EVENT_CONNECTED");
            esp_mqtt_client_subscribe(client, TOPIC_GPIO_OPEN, 1);
            esp_mqtt_client_subscribe(client, TOPIC_GPIO_CLOSE, 1);
            break;
        case MQTT_EVENT_DISCONNECTED:
            ESP_LOGI("MQTT_EVENT", "MQTT_EVENT_DISCONNECTED");
            break;
        case MQTT_EVENT_SUBSCRIBED:
            ESP_LOGI("MQTT_EVENT", "MQTT_EVENT_SUBSCRIBED");
//            esp_mqtt_client_publish(client, TOPIC_GPIO_OPEN, "1", 1, 0, 0);
            break;
        case MQTT_EVENT_UNSUBSCRIBED:
            ESP_LOGI("MQTT_EVENT", "MQTT_EVENT_UNSUBSCRIBED");
            break;
        case MQTT_EVENT_PUBLISHED:
            ESP_LOGI("MQTT_EVENT", "MQTT_EVENT_PUBLISHED");
            break;
        case MQTT_EVENT_DATA:
            ESP_LOGI("MQTT_EVENT", "MQTT_EVENT_DATA");
            printf("TOPIC=%s\r\n", event->topic);
            printf("DATA=%s\r\n", event->data);
            break;
        case MQTT_EVENT_BEFORE_CONNECT:
            ESP_LOGI("MQTT_EVENT", "MQTT_EVENT_BEFORE_CONNECT");
            break;
        case MQTT_EVENT_DELETED:
            ESP_LOGI("MQTT_EVENT", "MQTT_EVENT_DELETED");
            break;
        case MQTT_USER_EVENT:
            ESP_LOGI("MQTT_EVENT", "MQTT_USER_EVENT");
            break;
        default:
            break;
    }

}

void mqtt_connect(bool connect_wifi) {
    if (connect_wifi) {
        //启动wifi
        connect_wifi(KETING_WIFI, NULL);
    }
    //初始化mqtt客户端
    clientHandle = esp_mqtt_client_init(&clientConfig);
    //注册事件
    esp_mqtt_client_register_event(clientHandle, MQTT_EVENT_ANY, mqtt_event_handel, clientHandle);
    //开始
    esp_mqtt_client_start(clientHandle);
}